<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\JsonResponse;

class UserController extends Controller
{
    /**
     * 显示用户管理页面
     */
    public function index(Request $request): View
    {
        $perPage = 20;
        $query = User::with(['createdRooms', 'joinedRooms', 'orders']);

        // 搜索功能
        if ($request->filled('search')) {
            $search = $request->get('search');
            $query->where(function ($q) use ($search) {
                $q->where('nickname', 'like', "%{$search}%")
                  ->orWhere('phone', 'like', "%{$search}%");
            });
        }

        // 状态筛选
        if ($request->filled('status')) {
            $status = $request->get('status');
            if ($status === 'active') {
                $query->where('is_active', true);
            } elseif ($status === 'inactive') {
                $query->where('is_active', false);
            }
        }

        // 地区筛选
        if ($request->filled('province')) {
            $query->where('province', 'like', "%{$request->get('province')}%");
        }

        // 获取用户并计算统计数据
        $users = $query->paginate($perPage);
        
        // 为每个用户添加统计数据
        $users->getCollection()->transform(function ($user) {
            $user->rooms_count = $user->createdRooms->count() + $user->joinedRooms->count();
            $user->orders_count = $user->orders->count();
            return $user;
        });

        return view('admin.users.index', compact('users'));
    }


    /**
     * 显示用户详情页面
     */
    public function show(int $id): View
    {
        $user = User::with(['createdRooms', 'joinedRooms', 'orders'])->findOrFail($id);
        
        // 计算统计数据
        $user->rooms_count = $user->createdRooms->count() + $user->joinedRooms->count();
        $user->orders_count = $user->orders->count();
        
        return view('admin.users.show', compact('user'));
    }


    /**
     * 切换用户状态
     */
    public function toggleStatus(int $id): RedirectResponse
    {
        $user = User::findOrFail($id);
        $user->is_active = !$user->is_active;
        $user->save();

        $status = $user->is_active ? '启用' : '禁用';
        return redirect()->back()->with('success', "用户 {$user->nickname} 已{$status}");
    }

    /**
     * 获取用户列表API
     */
    public function list(Request $request): JsonResponse
    {
        $perPage = $request->get('per_page', 20);
        $query = User::with(['createdRooms', 'joinedRooms', 'orders']);

        // 搜索功能
        if ($request->filled('search')) {
            $search = $request->get('search');
            $query->where(function ($q) use ($search) {
                $q->where('nickname', 'like', "%{$search}%")
                  ->orWhere('phone', 'like', "%{$search}%");
            });
        }

        // 状态筛选
        if ($request->filled('status')) {
            $status = $request->get('status');
            if ($status === 'active') {
                $query->where('is_active', true);
            } elseif ($status === 'inactive') {
                $query->where('is_active', false);
            }
        }

        $users = $query->paginate($perPage);
        
        // 为每个用户添加统计数据
        $users->getCollection()->transform(function ($user) {
            $user->rooms_count = $user->createdRooms->count() + $user->joinedRooms->count();
            $user->orders_count = $user->orders->count();
            return $user;
        });

        return response()->json([
            'data' => $users->items(),
            'pagination' => [
                'current_page' => $users->currentPage(),
                'last_page' => $users->lastPage(),
                'per_page' => $users->perPage(),
                'total' => $users->total(),
            ]
        ]);
    }

    /**
     * 获取用户详情API
     */
    public function showApi(int $id): JsonResponse
    {
        $user = User::with(['createdRooms', 'joinedRooms', 'orders'])->findOrFail($id);
        
        // 计算统计数据
        $user->rooms_count = $user->createdRooms->count() + $user->joinedRooms->count();
        $user->orders_count = $user->orders->count();
        
        return response()->json(['data' => $user]);
    }

    /**
     * 获取用户统计API
     */
    public function stats(): JsonResponse
    {
        $stats = [
            'total_users' => User::count(),
            'active_users' => User::where('is_active', true)->count(),
            'inactive_users' => User::where('is_active', false)->count(),
            'today_registrations' => User::whereDate('created_at', today())->count(),
            'this_month_registrations' => User::whereMonth('created_at', now()->month)->count(),
        ];

        return response()->json(['data' => $stats]);
    }
}
